const Koa = require('koa')
const mime = require('mime-types')
const fs = require('fs')
const app = new Koa()
const onerror = require('koa-onerror')
const logger = require('koa-logger')
const path = require('path')

// error handler
onerror(app)

// middlewares
app.use(logger())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(async (ctx) => {
  let filePath = path.join(__dirname, ctx.url) // 图片地址
  let file = null
  try {
    console.log(filePath)
    file = fs.readFileSync(filePath) // 读取文件
  } catch (error) {
    filePath = path.join(__dirname, '/images/default.png') // 默认图片地址
    file = fs.readFileSync(filePath) // 读取文件
  }

  let mimeType = mime.lookup(filePath) // 读取图片文件类型
  ctx.set('content-type', mimeType) // 设置返回类型
  ctx.body = file // 返回图片
})

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
